import { getInfoUrl } from "../../utils/http";

Component({
  properties: {
    // 请求URL
    url: {
      type: String,
      value: getInfoUrl()
    },
    // 是否自动加载
    autoLoad: {
      type: Boolean,
      value: true
    }
  },

  data: {
    visible: false,      // 控制弹窗显示
    loading: false,      // 加载状态
    infoData: {          // 通知数据
      title: '',
      description: '',
      isDevOps: 0,
      isClose: 0
    }
  },

  methods: {
    // 获取通知数据
    fetchData() {
      if (!this.properties.url) return;

      this.setData({ loading: true });

      wx.request({
        url: this.properties.url,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            this.handleData(res.data);
          }
        },
        fail: (err) => {
          console.error('通知请求失败:', err);
        },
        complete: () => {
          this.setData({ loading: false });
        }
      });
    },

    // 处理返回数据
    handleData(data) {

      const shouldShow = data.isDevOps === 1;
      const infoData = {
        title: data.title || '系统通知',
        description: data.description || '',
        isDevOps: data.isDevOps || 0,
        isClose: data.isClose || 0
      };

      this.setData({
        infoData,
        visible: shouldShow
      });

      // 通知父组件可见性变化
      this.triggerEvent('visibility-change', {
        visible: shouldShow,
        infoData
      });
    },

    // 关闭弹窗
    handleClose() {
      this.setData({ visible: false });
      this.triggerEvent('close');

      // 如果需要关闭小程序
      if (this.data.infoData.isDevOps === 1) {
        wx.exitMiniProgram();
      }
    },

    // 手动显示弹窗
    show() {
      this.setData({ visible: true });
    },

    // 手动隐藏弹窗
    hide() {
      this.setData({ visible: false });
    }
  },

  lifetimes: {
    attached() {
      if (this.properties.autoLoad) {
        this.fetchData();
      }
    }
  }
});